package com.haiyi.software.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;

import com.haiyi.software.app.delegate.FragmentFaceDelegate;
import com.haiyi.software.chat.FaceAdapter;
import com.haiyi.software.chat.FacePageAdeapter;
import com.haiyi.software.mycontrols.CirclePageIndicator;
import com.haiyi.software.tools.L;

@SuppressLint("ValidFragment")
public class FragmentFace extends Fragment {

	private int mCurrentPage = 0;// 当前表情页

	private List<String> mFaceMapKeys;// 表情对应的字符串数组

	private ViewPager mFaceViewPager;// 表情选择ViewPager

	View thisView = null;

	View chatView = null;
	private FragmentFaceDelegate fragmentFaceDelegate;

	public FragmentFaceDelegate getFragmentFaceDelegate() {
		return fragmentFaceDelegate;
	}

	public void setFragmentFaceDelegate(
			FragmentFaceDelegate fragmentFaceDelegate) {
		this.fragmentFaceDelegate = fragmentFaceDelegate;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		thisView = inflater.inflate(R.layout.fragment_face, null); // super.onCreateView(inflater,
																	// container,
																	// savedInstanceState);
		// chatView = inflater.inflate(R.layout.activity_chat, null);
		getParameters();

		initData();
		initView();
		initFacePage();
		this.setFragmentFaceDelegate(MainApplication.getInstance().getHiChat());
		return thisView;

	}

	private void getParameters() {

		// editTextID = (Integer) this.getArguments().get("txtid");
		// mChatEditText = (EditText) chatView.findViewById(editTextID);
	}

	private void initView() {
		mFaceViewPager = (ViewPager) thisView.findViewById(R.id.face_pager);
	}

	private void initData() {
		// mWithJabberID = getIntent().getDataString().toLowerCase();//
		// 获取聊天对象的id
		// 将表情map的key保存在数组中
		Set<String> keySet = MainApplication.getInstance().getFaceMap()
				.keySet();
		mFaceMapKeys = new ArrayList<String>();
		mFaceMapKeys.addAll(keySet);
	}

	private void initFacePage() {
		// TODO Auto-generated method stub
		List<View> lv = new ArrayList<View>();
		for (int i = 0; i < MainApplication.NUM_PAGE; ++i)
			lv.add(getGridView(i));
		FacePageAdeapter adapter = new FacePageAdeapter(lv);
		mFaceViewPager.setAdapter(adapter);
		mFaceViewPager.setCurrentItem(mCurrentPage);
		CirclePageIndicator indicator = (CirclePageIndicator) thisView
				.findViewById(R.id.indicator);
		indicator.setViewPager(mFaceViewPager);
		adapter.notifyDataSetChanged();
		// mFaceRoot.setVisibility(View.GONE);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				mCurrentPage = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// do nothing
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// do nothing
			}
		});

	}

	private GridView getGridView(int i) {
		// TODO Auto-generated method stub
		GridView gv = new GridView(getActivity());
		gv.setNumColumns(7);
		gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
		gv.setBackgroundColor(Color.TRANSPARENT);
		gv.setCacheColorHint(Color.TRANSPARENT);
		gv.setHorizontalSpacing(1);
		gv.setVerticalSpacing(1);
		gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		gv.setGravity(Gravity.CENTER);
		gv.setAdapter(new FaceAdapter(thisView.getContext(), i));
		gv.setOnTouchListener(forbidenScroll());

		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == MainApplication.NUM) {// 删除键的位置
					fragmentFaceDelegate.DeleteFaceEvent();
				} else {
					int count = mCurrentPage * MainApplication.NUM + arg2;

					L.i("mCurrentPage", mCurrentPage + "");
					L.i("MainApplication.NUM", MainApplication.NUM + "");
					L.i("arg2", arg2 + "");
					L.i("count", count + "");

					// 注释的部分，在EditText中显示字符串
					// String ori = msgEt.getText().toString();
					// int index = msgEt.getSelectionStart();
					// StringBuilder stringBuilder = new StringBuilder(ori);
					// stringBuilder.insert(index, keys.get(count));
					// msgEt.setText(stringBuilder.toString());
					// msgEt.setSelection(index + keys.get(count).length());

					if (count < 85) {

						// 下面这部分，在EditText中显示表情
						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), (Integer) MainApplication
										.getInstance().getFaceMap().values()
										.toArray()[count]);
						if (bitmap != null) {
							int rawHeigh = bitmap.getHeight();
							int rawWidth = bitmap.getHeight();
							int newHeight = 50;
							int newWidth = 50;
							// 计算缩放因子
							float heightScale = ((float) newHeight) / rawHeigh;
							float widthScale = ((float) newWidth) / rawWidth;

							// 新建立矩阵
							Matrix matrix = new Matrix();
							matrix.postScale(heightScale, widthScale);
							// 设置图片的旋转角度
							// matrix.postRotate(-30);
							// 设置图片的倾斜
							// matrix.postSkew(0.1f, 0.1f);
							// 将图片大小压缩
							// 压缩后图片的宽和高以及kB大小均会变化
							Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0,
									0, rawWidth, rawHeigh, matrix, true);
							ImageSpan imageSpan = new ImageSpan(thisView
									.getContext(), newBitmap);

							String emojiStr = mFaceMapKeys.get(count);
							SpannableString spannableString = new SpannableString(
									emojiStr);
							spannableString.setSpan(imageSpan,
									emojiStr.indexOf('['),
									emojiStr.indexOf(']') + 1,
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

							// mChatEditText.append(spannableString);
							if (fragmentFaceDelegate != null)
								fragmentFaceDelegate
										.ReceiveFaceEvent(spannableString);

						} else {
							// String ori = mChatEditText.getText().toString();
							// int index = mChatEditText.getSelectionStart();
							// StringBuilder stringBuilder = new
							// StringBuilder(ori);
							// stringBuilder.insert(index,
							// mFaceMapKeys.get(count));
							// mChatEditText.setText(stringBuilder.toString());
							// mChatEditText.setSelection(index
							// + mFaceMapKeys.get(count).length());
						}
						if (bitmap != null && !bitmap.isRecycled()) {
							bitmap.recycle();
							bitmap = null;
						}
						System.gc();
					}
				}
			}
		});
		return gv;
	}

	// 防止乱pageview乱滚动
	private OnTouchListener forbidenScroll() {
		return new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					return true;
				}
				return false;
			}
		};
	}
}
